package androidcamp.socialfitnesstracker;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidcamp.socialfitnesstracker.data.WorkoutType;

public class DoingActivity extends Activity {

    private WorkoutActivityTimer timer;
    private Thread timerThread;
    private TextView timerReadout;
    private TextView activityReadout;
    public static final String ACTIVITY_TIME_SPENT = "TIME_SPENT";

    private WorkoutType workoutType;
    public static final String WORKOUT_ACTIVITY_TYPE = "WORKOUT_ACTIVITY_TYPE";
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.doing_activity);
        // start timer
        timerReadout = (TextView) findViewById(R.id.timerReadout);
        timer = new WorkoutActivityTimer(timerReadout);
        timerThread = new Thread(timer);
        timerThread.start();
        Log.d(WorkoutActivityTimer.LOG_TAG, "just started the thread");
        // set activity readout
        activityReadout = (TextView) findViewById(R.id.activityName);
        workoutType = (WorkoutType) getIntent().getExtras().get(NewWorkout.WORKOUT_TYPE);
        activityReadout.setText(workoutType.getHumanName());
        // set up finish handler
        ((Button) findViewById(R.id.doneButton)).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                try {
                    Intent resultData = new Intent();
                    resultData.putExtra(ACTIVITY_TIME_SPENT, timer.getElapsedTime());
                    resultData.putExtra(WORKOUT_ACTIVITY_TYPE, workoutType);
                    setResult(RESULT_OK, resultData);
                    finish();
                } catch (InterruptedException e) {
                    Log.e(WorkoutActivityTimer.LOG_TAG, "getElapsedTime interrupted!");
                }
            }
        });
    }

    public void onStop() {
        super.onStop();
        Log.d(WorkoutActivityTimer.LOG_TAG, "stopping timer thread");
        timerThread.interrupt();
    }

}
